package com.engine.hikvision.cron.door;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.hikvision.utils.HikVisionApiUtil;
import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.huawei.shade.org.joda.time.DateTime;
import com.huawei.shade.org.joda.time.format.DateTimeFormat;
import com.huawei.shade.org.joda.time.format.DateTimeFormatter;
import com.mzlion.core.lang.CollectionUtils;
import com.weaver.general.Util;
import org.apache.commons.lang.StringUtils;
import org.hsqldb.lib.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.schedule.BaseCronJob;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SyncDoorDataJob extends BaseCronJob {

    @Override
    public void execute() {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("begin do SyncDoorDataJob invoke ...");
        RecordSet rs = new RecordSet();
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(date);
        // 逻辑修改，现同步所有人当月的数据 2023-08-21
        String startTime = "";
        String endTime = format + "T23:59:59+08:00";

        // 逻辑修改，现同步所有人近七天的数据 2024-02-28
        LocalDate currentDate = LocalDate.now();
        // 获取前七天的日期
        LocalDate previousDate = currentDate.minusDays(7);
        LocalDate toDate = currentDate.plusDays(1);
        LocalDate tempDate = currentDate.minusDays(30);
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = previousDate.format(formatter);
        String tempDateStr = tempDate.format(formatter);
        String toDateStr = toDate.format(formatter);
        startTime = formattedDate + "T00:00:01+08:00";

        Map<String, Integer> certNoAndIdMap = getCertNoAndIdMap();
        String sql = "select * from HrmScheduleSign where belongdate between '" + tempDateStr + "' and '" + toDateStr + "'";
        baseBean.writeLog("SyncDoorDataJob sql is:" + sql);
        rs.execute(sql);
        List<List> allParams = new ArrayList<>();
        while (rs.next()) {
            List param = new ArrayList<String>();
            param.add(rs.getInt("userId"));
            param.add(rs.getString("userType"));
            param.add(rs.getString("signType"));
            param.add(rs.getString("signDate"));
            param.add(rs.getString("signTime"));
            param.add(rs.getString("isInCom"));
            param.add(rs.getString("signFrom"));
            param.add(rs.getString("timeZone"));
            param.add(rs.getString("belongdate"));
            param.add(rs.getString("addr"));
            allParams.add(param);
        }

        String workCodePrefixStr = baseBean.getPropValue("hikvisiondoorindexcode", "WORK_CODE_PREFIX");
        String doorIndexCodeStr = baseBean.getPropValue("hikvisiondoorindexcode", "ATTENDANCE_DOOR_INDEX_CODES");
        String[] doorIndexCodes = null;

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("pageSize", "1000");

        if (StringUtils.isNotEmpty(doorIndexCodeStr)) {
            Set<String> ryrqSet = new HashSet<>();
            doorIndexCodes = doorIndexCodeStr.split(",");
            for (String s : doorIndexCodes) {
                int pageNo = 1;
                boolean isGoing = true;
                List<String> tempIndexCodes = new ArrayList<>();
                tempIndexCodes.add(s);
                map.put("doorIndexCodes", tempIndexCodes.toArray());
                while (isGoing) {
                    try {
                        map.put("pageNo", String.valueOf(pageNo));
                        baseBean.writeLog("SyncDoorDataJob map:" + map);
                        String result = HikVisionApiUtil.callPostApiList("/api/acs/v2/door/events", map);
                        JSONObject obj = JSON.parseObject(result);
                        JSONObject dataObj = obj.getJSONObject("data");
                        JSONArray jsonList = dataObj.getJSONArray("list");
                        if (dataObj.getInteger("totalPage") > pageNo) {
                            pageNo += 1;
                        } else {
                            isGoing = false;
                        }
                        baseBean.writeLog("jsonList size:" + jsonList.size());
                        List<List> insertParams = new ArrayList<>();
                        for (int i = 0; i < jsonList.size(); i++) {
                            List insertParam = new ArrayList<String>();
                            JSONObject jsonObject = jsonList.getJSONObject(i);
                            String certNo = Util.null2String(jsonObject.getString("jobNo"));
                            if (StringUtil.isEmpty(certNo)) {
                                continue;
                            }
                            if (org.apache.commons.lang3.StringUtils.isNotEmpty(workCodePrefixStr) && !certNo.startsWith(workCodePrefixStr)) {
                                continue;
                            }
                            Integer userId = certNoAndIdMap.get(certNo);
                            String userType = "1";
                            String signType = jsonObject.getInteger("inAndOutType") == 1 ? "1" : "2";
                            String eventTime = jsonObject.getString("eventTime");
                            String [] arr = getDateStrFromIso8601(eventTime).split("\\s+");
                            String signDate = arr[0];
                            String signTime = arr[1];
                            String isInCom = "1";  // 1:有效; 0:无效
                            String signFrom = jsonObject.getString("doorName");
                            String timeZone = "GMT+8";
                            String belongdate = signDate;
                            insertParam.add(userId);
                            insertParam.add(userType);
                            insertParam.add(signType);
                            insertParam.add(signDate);
                            insertParam.add(signTime);
                            insertParam.add(isInCom);
                            insertParam.add("海康考勤机");
                            insertParam.add(timeZone);
                            insertParam.add(belongdate);
                            insertParam.add(signFrom);
                            insertParams.add(insertParam);

                            String key = userId + "=" + belongdate;
                            ryrqSet.add(key);
                        }
                        baseBean.writeLog("insertParams result:" + insertParams);
                        List<List> insertParamsNew = new ArrayList<>();
                        for (int i = 0; i < insertParams.size(); i++) {
                            if (!allParams.contains(insertParams.get(i))) {
                                insertParamsNew.add(insertParams.get(i));
                            }
                        }
                        if (CollectionUtils.isNotEmpty(insertParamsNew)) {
                            String insertSql = "INSERT INTO HrmScheduleSign(userId, userType, signType, signDate, signTime, isInCom, " +
                                    "signFrom, timeZone, belongdate, addr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                            rs.executeBatchSql(insertSql, insertParamsNew);
                        }
                    } catch (Exception e) {
                        isGoing = false;
                        baseBean.writeLog("SyncDoorDataJob eeror:" + e.getMessage());
                    }
                }
            }

            if (!org.springframework.util.CollectionUtils.isEmpty(ryrqSet)) {
                for (String key : ryrqSet) {
                    if (org.apache.commons.lang3.StringUtils.isEmpty(key)) {
                        continue;
                    }
                    String[] split = key.split("=");
                    String uid = split[0];
                    String dateT = split[1];
                    if (org.apache.commons.lang3.StringUtils.isEmpty(uid) || org.apache.commons.lang3.StringUtils.isEmpty(dateT)) {
                        continue;
                    }
                    new KQFormatBiz().formatDate(uid, dateT);
                    //处理加班生成
                    SplitActionUtil.pushOverTimeTasksAll(dateT, dateT, uid);
                }
            }
        }
        baseBean.writeLog("end do SyncDoorDataJob invoke  ...");
    }

    public String getDateStrFromIso8601(String dateStr){
        DateTimeFormatter dtf1 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");
        DateTime dt= dtf1.parseDateTime(dateStr);
        DateTimeFormatter dtf2= DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        return dt.toString(dtf2);
    }

    public Map<String, Integer> getCertNoAndIdMap() {
        Map<String, Integer> certNoAndIdMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        rs.execute("select id, workcode from hrmresource");
        while (rs.next()) {
            certNoAndIdMap.put(rs.getString("workcode"), rs.getInt("id"));
        }
        return certNoAndIdMap;
    }
}
